/**
 * 取中间文本
 * @param {string} s 源文本
 * @param {string} start 开始文本
 * @param {string} end 结束文本
 */
const takeMiddleText = (s, start, end) => {
  const beginIndex = s.indexOf(start) + start.length;
  const endIndex = s.indexOf(end, beginIndex);

  return s.slice(beginIndex, endIndex);
};

/**
 * 从互助码数据中解析出游戏数据
 * @param {string} data 互助码数据
 * @param {string} chineseGameName 游戏名
 * @param {number} jdAccountNumber 京东账号数
 */
const parseGameData = (data, chineseGameName, jdAccountNumber) => {
  const prefix = chineseGameName + '：\n';
  const suffix = '\n\n';
  const reg = /【京东账号(\d+)（.*）】(.+)/;
  const raw = takeMiddleText(data, prefix, suffix);
  const list = raw.split('\n');
  const o = {};

  list.forEach((value) => {
    const ret = reg.exec(value);
    const k = ret[1];
    const v = ret[2];
    o[k] = v;
  });

  for (let index = 1; index <= jdAccountNumber; index++) {
    const element = o[index];

    if (element === undefined) {
      o[index] = '';
    }
  }

  return o;
};

/**
 * 从游戏数据中生成互助关系
 * @param {object} data 游戏数据
 */
const generateMutualRelationship = (data) => {
  // 互助码键前缀
  const mutualCodeKeyPrefix = 'My';

  // 互助关系键前缀
  const mutualRelationsKeyPrefix = 'ForOther';

  // 游戏名
  const gameName = Object.keys(data)[0];

  // 游戏互助码
  const mutualGameCode = data[gameName];

  // 账号键列表
  const accountKeys = Object.keys(mutualGameCode);

  // 游戏的条目数据
  const gameEntriesData = Object.entries(mutualGameCode);

  // 一堆互助码
  const aPileMutualCode = gameEntriesData
    .map(([k, v]) => `${mutualCodeKeyPrefix}${gameName}${k}="${v}"`)
    .join('\n');

  // 一堆互助关系
  const aPileMutualRelations = accountKeys
    .map((ignoreKey) => {
      const relationKey = `${mutualRelationsKeyPrefix}${gameName}${ignoreKey}`;

      if (mutualGameCode[ignoreKey] === '') {
        return `${relationKey}=""`;
      }

      const relationValue = accountKeys
        .filter(
          (accountKey) =>
            accountKey !== ignoreKey && mutualGameCode[accountKey] !== '',
        )
        .map((accountKey) => `\${My${gameName}${accountKey}}`)
        .join('@');
      return `${relationKey}="${relationValue}"`;
    })
    .join('\n');

  return `################################## 定义${gameName}互助（选填） ##################################\n${aPileMutualCode}\n\n${aPileMutualRelations}`;
};

/**
 * 生成所有互助关系
 * @param {string} data 互助码数据
 * @param {string} someGameName 一些游戏名
 * @param {number} jdAccountNumber 京东账号数
 */
const generateAllMutualRelations = (data, someGameName, jdAccountNumber) => {
  return Object.entries(someGameName)
    .map(([k, v]) => {
      return generateMutualRelationship({
        [k]: parseGameData(data, v, jdAccountNumber),
      });
    })
    .join('\n\n\n');
};

module.exports = {
  takeMiddleText,
  parseGameData,
  generateMutualRelationship,
  generateAllMutualRelations,
};
